import { useEffect, useRef, useState } from 'react'
import { NavBar, Space } from 'antd-mobile'
import { PhoneFill, PictureOutline, AudioFill } from 'antd-mobile-icons'
import { useParams, useLocation, useNavigate } from 'react-router-dom'
import axios from '../../utils/index'
import dayjs from 'dayjs'
import { io } from 'socket.io-client'
import './Chat.scss'
export default function Chat() {
    let { id } = useParams()
    let { state } = useLocation()
    let navigate = useNavigate()
    let [message, setMessage] = useState([])
    let [arrivalMessage, setArrivalMessage] = useState([])
    let [value, setValue] = useState('')
    let chat = useRef(null)
    let socket = useRef()
    let userid = localStorage.getItem('userid')
  
    
    useEffect(() => {
        socket.current = io('ws://localhost:8900')
        socket.current.on('getMessage', (data) => {
            setArrivalMessage({
                sender: data.senderId,
                text: data.text,
                createdAt: Date.now()
            })
        })
    }, [])

    useEffect(() => {
        arrivalMessage && setMessage((prev) => [...prev, arrivalMessage])
    },[arrivalMessage])

    useEffect(() => {
        socket.current.emit('addUser', userid)
        socket.current.on('getUsers', (users) => {
            console.log(users);
        })
    }, [userid])

    useEffect(() => {
        getMessage()
    }, [id])

    useEffect(() => {
        chat.current?.scrollIntoView({ behavior: 'smooth' })
    }, [message])

    const getMessage = () => {
        axios.get(`/getmessage/${id}`).then(res => {
            setMessage(res.data)
        })
    }

    const sendMessage = () => {

        socket.current.emit('sendMessage', {
            senderId: localStorage.getItem('userid'),
            receiverId: state.id,
            text: value
        })

        axios.post('/addmessage', { conversationId: id, sender: localStorage.getItem('userid'), text: value }).then(() => {
            getMessage()
        })
    }

    const right = (
        <div style={{ fontSize: 24 }}>
            <Space style={{ '--gap': '16px' }}>
                <PhoneFill />
            </Space>
        </div>
    )

    const back = () => {
        navigate(-1)
    }
    return (
        <div>
            <NavBar back={<span className='back'>{state.username}</span>} onBack={back} right={right}></NavBar>
            <div className='chat' >
                {message.map((item) => {
                    return <div key={item._id} ref={chat} className={`${item.sender === localStorage.getItem('userid') ? 'right' : 'left'}`}>
                        <span>{item.text}</span>
                        <span className='time'>{dayjs(item.createDate).format('HH:mm')}</span>
                    </div>
                })}
            </div>
            <div className='footer'>
                <input type="text" placeholder='请输入内容' className='input' value={value}
                    onChange={(e) => { setValue(e.target.value) }}
                    onKeyDown={(e) => {
                        if (e.keyCode === 13) {
                            sendMessage()
                            setValue("")
                        }
                    }}
                />
                <button className='phone'><PictureOutline /></button>
                <button className='send'><AudioFill /></button>
            </div>
        </div>
    )
}
